package com.example.administrator.systemfailreport.utils;

import android.content.Context;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Handler;

/**
 * Created by Administrator on 2017/2/13.
 */
public class HttpUtils {
    private static Object	   CONNECTION_TIMEOUT	= 3 * 1000;


    private static CookieStore cookieStore	      = null;
    private static String	   USER_AGENT	      = "Android";
    /**
     * 用户登录验证
     * @param username
     * @param pwd
     * @param ac
     * @return successFlag = "1"
     * @throws Exception
     */
    public static void login(final Handler handler,final String username,final String pwd,final Context ac) throws Exception {
        try {
                String httpUrl = "";
                Map<String, String> params = new HashMap<>();
                params.put("username", username);
                params.put("password", pwd);
                StringBuffer strResult = queryStringForPost(httpUrl, params, ac);
                if(null!= strResult&&!"".equals(strResult)
                        ) {
                    JSONObject jresult = new JSONObject(strResult.toString());
                    String state = JsonUtil.getJsonValue(jresult,"state");
                    if ("Success".equals(state)){

                    }else if ("Fail".equals(state)){

                    }
                }


        }catch (JSONException e) {
            e.printStackTrace();
        }

    }
    /**
     * 以传统模式提交数据
     * @param url
     * @param entity
     * @return
     */
    public static String doPost(String url,HttpEntity entity,Context ctx) {
        HttpPost request = new HttpPost(url);
        request.setEntity(entity);
        System.out.println("执行了dopost="+request);
        return doPostWithCookie(request, ctx);
    }

    /**
     * 以ajax的形式提交数据
     * @param url
     * @param entity
     * @return
     */
    public static String doAjaxPost(String url,HttpEntity entity,Context ctx) {
        HttpPost request = new HttpPost(url);
        request.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
        request.setEntity(entity);
        System.out.println("执行了doajax="+request);
        return doPostWithCookie(request, ctx);
    }




    /**
     * 附加cookie提交数据
     * @param request
     * @return
     */
    public static String doPostWithCookie(HttpUriRequest request,Context ctx) {
        String result = null;
        HttpParams httpParams = new BasicHttpParams();
        try {
            HttpProtocolParams.setUserAgent(httpParams, USER_AGENT);
            DefaultHttpClient dhc = new DefaultHttpClient(httpParams);
            dhc.setCookieStore(cookieStore);
            dhc.getParams()
                    .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, CONNECTION_TIMEOUT);
            HttpResponse response = dhc.execute(request);
            System.out.println("执行了cookie");
            if(response.getStatusLine().getStatusCode() == 200) {
                cookieStore = dhc.getCookieStore();
                result = EntityUtils.toString(response.getEntity(), "UTF-8");
                System.out.println("cookie="+result);
            } else if(response.getStatusLine().getStatusCode() == 404) {
                System.out.println("cookie="+404);
            } else if(response.getStatusLine().getStatusCode() == 503) {
                System.out.println("cookie="+503);
            }

            if(request.isAborted()) {
                request.abort();
            }
            return result;
        } catch (ConnectTimeoutException e) {
            //DeviceTool.makeToast(ctx, "网络超时，请重试。。。", false);
            e.printStackTrace();
            return "";
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            result = "网络失效";
            return result;
        } catch (IOException e) {
            e.printStackTrace();
            result = "网络失效";
            return result;
        }
    }
    /**
     * 通过url发送post请求，返回请求结果
     * @param url
     * @param params
     * @return
     */
    public static StringBuffer queryStringForPost(String url,Map<String, String> params,Context ctx) {
        try {
            List<NameValuePair> msg = new ArrayList<NameValuePair>();
            JSONObject jobj = new JSONObject();
            for(String key : params.keySet()) {
                jobj.put(key, params.get(key));
            }
            System.out.println("jobj="+jobj);
            msg.add(new BasicNameValuePair("updateRecord", jobj.toString()));
            HttpEntity entity = new UrlEncodedFormEntity(msg, StandardCharsets.UTF_8);
            String r = doAjaxPost(url, entity, ctx);
            return r == null ? null : new StringBuffer(r);
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 通过url发送post请求，返回请求结果
     * @param url
     * @param params
     * @return
     */
    public static StringBuffer queryStringForPostTwo(String url,Map<String, String> params,Context ctx) {
        try {
            List<NameValuePair> msg = new ArrayList<NameValuePair>();
            JSONObject jobj = new JSONObject();
            for(String key : params.keySet()) {
                jobj.put(key, params.get(key));
            }
            System.out.println("jobj="+jobj);
            msg.add(new BasicNameValuePair("params", jobj.toString()));
            HttpEntity entity = new UrlEncodedFormEntity(msg,StandardCharsets.UTF_8);
            String r = doAjaxPost(url, entity, ctx);
            return r == null ? null : new StringBuffer(r);
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 通过url发送post请求，返回请求结果
     * @param url
     * @param ctx
     * @return
     */
    public static StringBuffer queryStringForPostTwo(String url,Context ctx) {
        try {
            List<NameValuePair> msg = new ArrayList<NameValuePair>();
            HttpEntity entity = new UrlEncodedFormEntity(msg, StandardCharsets.UTF_8);
            String r = doAjaxPost(url, entity, ctx);
            return r == null ? null : new StringBuffer(r);
        }  catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
